package pers.smalltown.authorize.wechat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import pers.smalltown.authorize.consts.Consts;
import pers.smalltown.authorize.wechat.dto.WxAccessToken;

@Component
public class WechatUtils {
	private static Logger logger = LoggerFactory.getLogger(WechatUtils.class);

	public WxAccessToken getOpenId(String authCode) throws JsonMappingException, JsonProcessingException {
		String wxAccessUri = Consts.getWxAccessUri(authCode);
		RestTemplate restTemplate = new RestTemplate();
		String resultStr = restTemplate.getForObject(wxAccessUri, String.class);
		logger.debug("wx access resultStr: {}", resultStr);
		ObjectMapper resultMapper = new ObjectMapper();
		resultMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		WxAccessToken result = resultMapper.readValue(resultStr, WxAccessToken.class);
		
		logger.debug("wx access token: {}", result);
		String openid = result.getOpenid();
		if (openid != null) {
			WxGlobalData.setWxOpenIdCache(openid, result);
			WxGlobalData.setWxAuthCodeCache(authCode, openid);
		}
		return result;
	}
}
